package org.example.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.example.common.BaseContext;
import org.example.common.R;
import org.example.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
@Component
public class loginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Autowired
    private EmployeeService employeeService;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String requestURI = request.getRequestURI();

        //1.如果匹配路径，则放行
        String[] urls = {"/employee/login", "/employee/logout", "/backend/**", "/front/**","/druid/**"};
        boolean check = check(urls, requestURI);
        if (check){
            filterChain.doFilter(request,servletResponse);
            return;
        }
        //2.如果已经登陆，则放行
        Long id = (Long)request.getSession().getAttribute("employee");
        if(!(Objects.isNull(id) || Objects.isNull(employeeService.getById(id)))){
            BaseContext.setCurrentId(id);
            filterChain.doFilter(request,servletResponse);
            return;
        }
        //3.未登陆，返回未登录信息
        servletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
